package com.itheima.service;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.dao.UploadFileDao;
import com.itheima.po.UploadFile;

@Service
public class FilenameServiceImpl implements FilenameService {

	@Autowired
	private UploadFileDao uploadFileDao;

	@Override
	public String handleFormUpload(String name, List<MultipartFile> uploadfile, HttpServletRequest request,
			Model model) {
		String originalFilename = "";
		String newFilename = "";
		// 判断所上传文件是否存在
		if (!uploadfile.isEmpty() && uploadfile.size() > 0) {
			// 循环输出上传的文件
			for (MultipartFile file : uploadfile) {
				// 获取上传文件的原始名称
				originalFilename = file.getOriginalFilename();
				// 设置上传文件的保存地址目录
				String dirPath = request.getServletContext().getRealPath("/upload/");
				File filePath = new File(dirPath);
				// 如果保存文件的地址不存在，就先创建目录

				System.out.println("文件路径" + filePath.getPath());
				if (!filePath.exists()) {
					filePath.mkdirs();
				}
				// 使用UUID重新命名上传的文件名称(上传人_uuid_原始文件名称)
//				String newFilename = name+ "_"+UUID.randomUUID() + 
//                                                   "_"+originalFilename;
				String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
				String prefix = originalFilename.substring(0, originalFilename.lastIndexOf("."));
				newFilename = prefix + "-" + name + "." + suffix;

				model.addAttribute("filename", newFilename);
				System.out.println("路径：" + dirPath + newFilename);

				try {
					// 使用MultipartFile接口的方法完成文件上传到指定位置
					file.transferTo(new File(dirPath + newFilename));
				} catch (Exception e) {
					e.printStackTrace();
					return "error";
				}
			}

//			 List<UploadFile> list= uploadFileDao.findAllUploadFile();
//			 System.out.println(list);
			// 跳转到成功页面
			// return "fileList";
			return newFilename;
		} else {
			return "error";
		}
	}

	@Override
	public ResponseEntity<byte[]> fileDownload(HttpServletRequest request, String filename) throws IOException {
		// 指定要下载的文件所在路径
		String path = request.getServletContext().getRealPath("/upload/");
		// 创建该文件对象
		File file = new File(path + File.separator + filename);
		// 对文件名编码，防止中文文件乱码
		filename = this.getFilename(request, filename);
		// 设置响应头
		HttpHeaders headers = new HttpHeaders();
		// 通知浏览器以下载的方式打开文件
		headers.setContentDispositionFormData("attachment", filename);
		// 定义以流的形式下载返回文件数据
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		// 使用Sring MVC框架的ResponseEntity对象封装返回下载数据
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
	}

	@Override
	public String getFilename(HttpServletRequest request, String filename) throws UnsupportedEncodingException {
		// IE不同版本User-Agent中出现的关键词
		String[] IEBrowserKeyWords = { "MSIE", "Trident", "Edge" };
		// 获取请求头代理信息
		String userAgent = request.getHeader("User-Agent");
		for (String keyWord : IEBrowserKeyWords) {
			if (userAgent.contains(keyWord)) {
				// IE内核浏览器，统一为UTF-8编码显示
				return URLEncoder.encode(filename, "UTF-8");
			}
		}
		// 火狐等其它浏览器统一为ISO-8859-1编码显示
		return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
	}

	@Override
	public PageInfo<UploadFile> findByPage(Integer pageNum, Integer pageSize) {
		// 启动分页
		PageHelper.startPage(pageNum, pageSize);

		// 查询所有的用户信息
		List<UploadFile> users = uploadFileDao.findAllUploadFile();

		// 封装分页对象
		PageInfo<UploadFile> pageInfo = new PageInfo<>(users);

		// 返回数据
		return pageInfo;

	}

	@Override
	public List<UploadFile> findByCondition(String filename) {
		return uploadFileDao.findByCondition(filename);
	}

	@Override
	public UploadFile findById(Integer id) {
		// TODO 自动生成的方法存根
		return uploadFileDao.findUploadFileById(id);
	}

	@Override
	public int addFile(UploadFile uploadFile) {
		return uploadFileDao.addFile(uploadFile);
	}

	@Override
	public int updateUploadFile(UploadFile uploadfile) {
		// TODO 自动生成的方法存根
		return uploadFileDao.updateUploadFile(uploadfile);
	}

	@Override
	public int deleteFile(Integer id) {
		// TODO 自动生成的方法存根
		return uploadFileDao.deleteFile(id);
	}

	/**
	 * 通过文件路径直接修改文件名
	 *
	 * @param filePath    需要修改的文件的完整路径
	 * @param newFileName 需要修改的文件的名称
	 * @return
	 */
	public String FixFileName(HttpServletRequest request, String oldFileName, String newFileName) {

		String dirPath = request.getServletContext().getRealPath("/upload/");
		System.out.println("更新。。。文件路经：" + dirPath);
		File f = new File(dirPath + oldFileName);

		System.out.println("文件路径" + f.getPath());
		if (!f.exists()) {
			f.mkdirs();
		}

		File nf = new File(dirPath + newFileName);
		System.out.println("新文件名路径..." + nf.getPath());
		try {
			f.renameTo(nf); // 修改文件名
			System.out.println("新路径。。。。" + f.getPath());
		} catch (Exception err) {
			err.printStackTrace();
			return null;
		}
		return newFileName;
	}

}
